package cn.hg.solon.youcan.flex.util;

import com.mybatisflex.core.query.QueryColumn;
import com.mybatisflex.core.query.QueryOrderBy;
import com.mybatisflex.core.query.QueryWrapper;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.text.CharSequenceUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.db.Page;
import org.dromara.hutool.db.sql.Direction;
import org.dromara.hutool.db.sql.Order;

public class QueryWrapperUtil {

    public static QueryWrapper applyOrderBy(QueryWrapper query, Page page) {
        if (ObjUtil.isNull(page)) {
            return query;
        }

        Order[] orders = page.getOrders();
        if (ArrayUtil.isNotEmpty(orders)) {
            for (Order order : orders) {
                query.orderBy(new QueryOrderBy(new QueryColumn(CharSequenceUtil.toUnderlineCase(order.getField())),
                        ObjUtil.isNull(order.getDirection()) ? Direction.ASC.name() :
                                order.getDirection().name()));
            }
        }

        return query;
    }

    public static QueryWrapper applyOrderBy(QueryWrapper query, Order order) {
        if (ObjUtil.isNull(order)) {
            return query;
        }
        return query.orderBy(new QueryOrderBy(new QueryColumn(CharSequenceUtil.toUnderlineCase(order.getField())),
                ObjUtil.isNull(order.getDirection()) ? Direction.ASC.name() :
                order.getDirection().name()));
    }
}
